﻿using HuaCheng.CommonClass;
using HuaCheng.Model;
using Longbow.Data;
using Longbow.ExceptionManagement;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;
using System.IO;

namespace HuaCheng.DataAccess
{
    /// <summary>
    /// 通道数据类的数据库操作
    /// </summary>
    class ChannelDataHelper
    {
        //增加日志记录
        public static log4net.ILog log = log4net.LogManager.GetLogger("Huacheng.Logging");
        //初始化导出hd文件进度条步长的委托和方法
        public delegate void InitProcessBar(int maxNum, int step);
        public static event InitProcessBar InitProcessBarStep;
        //增加导出hd文件进度条值的委托和方法
        public delegate void AddProcessBar();
        public static event AddProcessBar AddProcessBarStep;
        public static void OnInitProcessBarStep(int maxNum, int step)
        {
            InitProcessBarStep(maxNum, step);
        }

        public static void OnAddProcessBarStep()
        {
            AddProcessBarStep();
        }
        /// <summary>
        /// 向通道数据表中插入数据
        /// </summary>
        /// <param name="channelState"></param>
        /// <param name="devId"></param>
        public static void InsertChannelData(ChannelState channelState, string tableName, string circ, string testid, int testmode, int stepNum, int stepType, int workType, int testtime, string paStr, bool isExtraData, List<AuxChannel> auxData)
        {
            if (channelState == null) throw new ArgumentNullException("channelState");
            string sql = "insert into " + tableName + "(pulse_num,test_id,test_mode,mid_id,cabinet_id,channel_num,isAll,step_num,step_type,work_type,cycle,test_time,Channel_efficiency,DC_outputVolt," +
            "DC_loadCurrent,Load_temper1,Load_temper2,DC_busVolt,Charge_cap,Discharge_cap,Total_cap,Step_time,Charge_energy,Discharge_energy,Total_energy,power,Diff_volt,Diff_current," +
            "Aux_data,Status_data,Sys_time,isExtra) values(@pulse_num,@testid,@test_mode,@mid,@gid,@cid,@isAll,@stepnum,@steptype,@worktype,@circ,@testtime,@chlefc,@dcoutvol,@dcloadcur,@loadtemp1,@loadtemp2,@dcbusvol," +
            "@chrcap,@dischrcap,@totalcap,@steptime,@charenrgy,@discharenrgy,@totalenergy,@power,@diffvol,@diffcur,@auxdata,@status_data,@systime,@isExtra)";
            try
            {
                using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
                {
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@pulse_num", channelState.pulseNumber));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", testid));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@test_mode", testmode));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@mid", channelState.MID + 1));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@gid", channelState.GID + 1));
                    if (paStr == "")
                    {
                        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", Convert.ToString(channelState.CID + 1)));
                        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@isAll", 0));
                    }
                    else
                    {
                        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", paStr));
                        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@isAll", Convert.ToInt32(channelState.CID + 1)));
                    }
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@stepnum", stepNum));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@steptype", stepType));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@worktype", workType));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@circ", circ));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testtime", testtime));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@chlefc", channelState.channelEfficiency));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@dcoutvol", channelState.DC_outputVolt));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@dcloadcur", channelState.DC_loadCurrent));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@loadtemp1", channelState.DC_loadTemper));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@loadtemp2", channelState.DC_ambientTemper));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@dcbusvol", channelState.DC_busVolt));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@chrcap", channelState.chargeCap));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@dischrcap", channelState.dischargeCap));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@totalcap", channelState.totalCap));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@steptime", channelState.stepTime));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@charenrgy", channelState.chargeEnergy));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@discharenrgy", channelState.dischargeEnergy));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@totalenergy", channelState.totalEnergy));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@power", channelState.power));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@diffvol", channelState.diffVolt));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@diffcur", channelState.diffCurrent));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@auxdata", JsonHelper.Serialize(auxData)));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@status_data", channelState.faultStatus));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@systime", channelState.time));
                    if (isExtraData)
                    {
                        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@isExtra", 1));
                    }
                    else
                    {
                        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@isExtra", 0));
                    }
                    DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
        }
        /// <summary>
        /// sql Server批量插入
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static bool InsertChannelData(DataTable dt, string tableName)
        {
            bool ret = false;
            using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
            {
                try
                {
                    using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction))
                    {
                        bulk.DestinationTableName = tableName;
                        bulk.WriteToServer(dt);
                    }
                    transaction.CommitTransaction();
                    ret = true;
                }
                catch (Exception ex)
                {
                    transaction.RollbackTransaction();
                    ExceptionManager.Publish(ex);
                }
            }
            return ret;
        }

        /// <summary>
        /// 一次事务提交多个sql语句
        /// </summary>
        /// <param name="SQLStringList"></param>
        public static void InsertChannelData(List<String> SQLStringList)
        {
            using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
            {
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, strsql))
                            {
                                DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
                            }
                        }
                    }
                    transaction.CommitTransaction();
                }
                catch (Exception ex)
                {
                    transaction.RollbackTransaction();
                    ExceptionManager.Publish(ex);
                }
            }
        }

        /// <summary>
        /// MySqlBulkLoader批量插入数据库
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public static int BulkInsert(DataTable table, string fileName)
        {
            if (string.IsNullOrEmpty(table.TableName)) throw new Exception("请给DataTable的TableName属性附上表名称");
            if (table.Rows.Count == 0) return 0;
            int insertCount = 0;
            string tmpPath = Path.Combine(Directory.GetCurrentDirectory(), fileName + ".csv"); //Path.GetTempFileName();
            //string tmpPath = Path.GetTempFileName(); //Path.GetTempFileName();
            //string tmpPath = Path.Combine(Directory.GetCurrentDirectory(), "Temp.csv"); 
            string csv = DataTableToCsv(table);
            File.WriteAllText(tmpPath, csv);
            using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
            {
                try
                {
                    MySqlBulkLoader bulk = new MySqlBulkLoader((MySqlConnection)transaction.Transaction.Connection)
                    {
                        FieldTerminator = ",",
                        FieldQuotationCharacter = '"',
                        EscapeCharacter = '"',
                        LineTerminator = "\r\n",
                        FileName = tmpPath,
                        NumberOfLinesToSkip = 0,
                        TableName = table.TableName,
                    };
                    insertCount = bulk.Load();
                    transaction.CommitTransaction();
                }
                catch (MySqlException ex)
                {
                    transaction.RollbackTransaction();
                    ExceptionManager.Publish(ex);
                }
            }
            File.Delete(tmpPath);
            return insertCount;
        }

        ///将DataTable转换为标准的CSV  
        /// </summary>  
        /// <param name="table">数据表</param>  
        /// <returns>返回标准的CSV</returns>  
        private static string DataTableToCsv(DataTable table)
        {
            //以半角逗号（即,）作分隔符，列为空也要表达其存在。  
            //列内容如存在半角逗号（即,）则用半角引号（即""）将该字段值包含起来。  
            //列内容如存在半角引号（即"）则应替换成半角双引号（""）转义，并用半角引号（即""）将该字段值包含起来。  
            StringBuilder sb = new StringBuilder();
            DataColumn colum;
            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    colum = table.Columns[i];
                    if (i != 0) sb.Append(",");
                    if (colum.DataType == typeof(string) && row[colum].ToString().Contains(","))
                    {
                        sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\"");
                    }
                    else sb.Append(row[colum].ToString());
                }
                sb.AppendLine();
            }
            return sb.ToString();
        }
        //public static int BulkInsert(string connectionString, DataTable table)
        //{
        //    if (string.IsNullOrEmpty(table.TableName)) throw new Exception("请给DataTable的TableName属性附上表名称");
        //    if (table.Rows.Count == 0) return 0;
        //    int insertCount = 0;
        //    string tmpPath = Path.Combine(Directory.GetCurrentDirectory(), "Temp.csv"); //Path.GetTempFileName();
        //    string csv = DataTableToCsv(table);
        //    File.WriteAllText(tmpPath, csv);
        //    using (MySqlConnection conn = new MySqlConnection(connectionString))
        //    {
        //        try
        //        {
        //            //Stopwatch stopwatch = new Stopwatch();
        //            //stopwatch.Start();
        //            conn.Open();
        //            MySqlBulkLoader bulk = new MySqlBulkLoader(conn)
        //            {
        //                FieldTerminator = ",",
        //                FieldQuotationCharacter = '"',
        //                EscapeCharacter = '"',
        //                LineTerminator = "\r\n",
        //                FileName = tmpPath,
        //                NumberOfLinesToSkip = 0,
        //                TableName = table.TableName,

        //           };
        //            insertCount = bulk.Load();
        //            //stopwatch.Stop();
        //            //Console.WriteLine("耗时:{0}", stopwatch.ElapsedMilliseconds);
        //        }
        //        catch (MySqlException ex)
        //        {
        //           throw ex;
        //        }
        //    }
        //    File.Delete(tmpPath);
        //    return insertCount;
        //}

        /// <summary>
        /// 如果不存在当日的数据表，则新建数据表
        /// </summary>
        /// <param name="devId"></param>
        /// <returns></returns>
        public static string CreateTodayTable(string ip,int cid)        {
            DateTime data = System.DateTime.Now;
            string[] str = ip.Split(new char[] { '.' });
            string name = str[0] + '_' + str[1] + "_" + str[2] + "_" + str[3]+"_"+cid;
            string tableName = "channeldata_" + name + "_" + data.Year + "_" + data.Month + "_" + data.Day;
            string newname = str[0] + '_' + str[1] + "_" + str[2] + "_" + str[3] + "_" + cid;
            string newtableName = "channeldata_" + newname + "_" + data.Year + "_" + data.Month + "_" + data.Day;
            try
            {
                string sql = "create table if not exists " + tableName +
                    "(seq_id int(11) NOT NULL AUTO_INCREMENT," +
                    "pulse_num int(11) NOT NULL," +
                    "test_id varchar(255) NOT NULL," +
                    "test_mode int(11) NOT NULL," +
                    "mid_id int(11) NOT NULL," +
                    "cabinet_id int(11) NOT NULL," +
                    "channel_num varchar(255) NOT NULL," +
                    "isAll int(11) NOT NULL," +
                    "step_num int(11) NOT NULL," +
                    "step_type int(11) NOT NULL," +
                    "work_type int(11) DEFAULT NULL," +
                    "cycle varchar(255) DEFAULT NULL," +
                    "test_time int(11) DEFAULT NULL," +
                    "Channel_efficiency int DEFAULT NULL," +
                    "DC_outputVolt float DEFAULT NULL," +
                    "DC_loadCurrent float DEFAULT NULL," +
                    "Load_temper1 float DEFAULT NULL," +
                    "Load_temper2 float DEFAULT NULL," +
                    "DC_busVolt float DEFAULT NULL," +
                    "Charge_cap float DEFAULT NULL," +
                    "Discharge_cap float DEFAULT NULL," +
                    "Total_cap float DEFAULT NULL," +
                    "Step_time float DEFAULT NULL," +
                    "Charge_energy float DEFAULT NULL," +
                    "Discharge_energy float DEFAULT NULL," +
                    "Total_energy float DEFAULT NULL," +
                    "power float DEFAULT NULL," +
                    "Diff_volt float DEFAULT NULL," +
                    "Diff_current float DEFAULT NULL," +
                    "Aux_data text DEFAULT NULL," +
                    "Status_data varchar(255) DEFAULT NULL," +
                    "Sys_time varchar(255) DEFAULT NULL," +
                    "isExtra int(11) DEFAULT NULL," +
                    "PRIMARY KEY (seq_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";                 
                DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
                DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
            }
            return tableName;
        }
        /// <summary>
        /// 返回当前测试记录条数
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="testId"></param>
        /// <returns></returns>
        public static int GetRecordNums(StepSetInfo stepSetInfo)
        {
            int records = 0;
            DateTime data = System.DateTime.Now;
            string[] str = stepSetInfo.DevIp.Split(new char[] { '.' });
            string name = str[0] + '_' + str[1] + "_" + str[2] + "_" + str[3];
            string tableName = "channeldata_" + name + "_" + data.Year + "_" + data.Month + "_" + data.Day;
            string sqlStr = "select count(*) from " + tableName + " where test_id=@testid and mid_id = @mid and cabinet_id=@gid and channel_num = @cid";
            try
            {
                using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sqlStr))
                {
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", stepSetInfo.TestId));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@mid", stepSetInfo.Mid));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@gid", stepSetInfo.Gid));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", Convert.ToString(stepSetInfo.Cid)));
                    records = Convert.ToInt32(DBAccessManager.SqlDBAccess.ExecuteScalar(cmd));
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
            return records;
        }
        /// <summary>
        /// 查询通道详细信息
        /// </summary>
        /// <param name="testId"></param>
        /// <param name="gid"></param>
        /// <param name="cid"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static List<ChannelState> RetriveChannelData(string testId, int mid, int gid, string cid, int startId, int detailNum, string tableName)
        {
            List<ChannelState> chls = new List<ChannelState>();
            //string sql = "select * from " + tableName + " where test_id = @testid and cabinet_num = @gid and channel_num = @cid and seq_id between @startNum and @lastNum order by Sys_time";
            string sql = "select * from " + tableName + " where test_id = @testid and mid_id = @mid and cabinet_id=@gid and channel_num = @cid and seq_id>=@startNum order by Sys_time limit @detailNum";
            try
            {
                using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
                {
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@startNum", startId));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", testId));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@mid", mid));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@gid", gid));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", Convert.ToString(cid)));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@detailNum", detailNum));//startId+detailNum-1
                    DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd);
                    while (reader.Read())
                    {
                        ChannelState chl = new ChannelState()
                        {
                            TestId = Convert.ToString(reader["test_id"]),
                            StepNum = Convert.ToInt32(reader["step_num"]),
                            StepType = Convert.ToInt32(reader["step_type"]),
                            Cycle = Convert.ToString(reader["cycle"]),
                            TestTime = Convert.ToInt32(reader["test_time"]),
                            MID = Convert.ToInt32(reader["mid_id"]),
                            GID = Convert.ToInt32(reader["cabinet_id"]),
                            CID = Convert.ToInt32(reader["channel_num"]),
                            channelEfficiency = Convert.ToInt32(reader["Channel_efficiency"]),
                            DC_outputVolt = Convert.ToSingle(reader["DC_outputVolt"]),
                            DC_loadCurrent = Convert.ToSingle(reader["DC_loadCurrent"]),
                            DC_loadTemper = Convert.ToSingle(reader["Load_temper1"]),
                            DC_ambientTemper = Convert.ToSingle(reader["Load_temper2"]),
                            DC_busVolt = Convert.ToSingle(reader["DC_busVolt"]),
                            chargeCap = Convert.ToSingle(reader["Charge_cap"]),
                            dischargeCap = Convert.ToSingle(reader["Discharge_cap"]),
                            totalCap = Convert.ToSingle(reader["Total_cap"]),
                            stepTime = Convert.ToSingle(reader["step_time"]),
                            chargeEnergy = Convert.ToSingle(reader["Charge_energy"]),
                            dischargeEnergy = Convert.ToSingle(reader["Discharge_energy"]),
                            totalEnergy = Convert.ToSingle(reader["Total_energy"]),
                            power = Convert.ToSingle(reader["power"]),
                            diffVolt = Convert.ToSingle(reader["Diff_volt"]),
                            diffCurrent = Convert.ToSingle(reader["Diff_current"]),
                            //auxTemper = Convert.ToSingle(reader["Aux_temper"]),
                            //auxVolt = Convert.ToSingle(reader["Aux_volt"]),
                            SysTime = Convert.ToString(reader["Sys_time"])
                        };
                        chls.Add(chl);

                    }
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
            return chls;
        }
        /// <summary>
        /// 查询该次测试的所有数据
        /// </summary>
        /// <param name="testId"></param>
        /// <param name="gid"></param>
        /// <param name="cid"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static List<string> RetriveAllChannelData(string testId, string ip, int mid, int gid, string cid, string tableName, List<int> recordcount, Dictionary<int, int> worktypeDic)
        {
            #region 原来代码
            //List<ChannelDataTab> chlList = new List<ChannelDataTab>();
            //string sql = "select * from " + tableName + " where test_id = @testid and mid_id = @mid and cabinet_id = @gid and channel_num = @cid and isExtra = 0";
            //try
            //{
            //    using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
            //    {
            //        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", testId));
            //        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@mid", mid));
            //        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@gid", gid));
            //        cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", cid));
            //        DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd);
            //        while (reader.Read())
            //        {
            //            ChannelDataTab chl = new ChannelDataTab()
            //            {
            //                SeqId = Convert.ToInt32(reader["seq_id"]),
            //                TestId = Convert.ToString(reader["test_id"]),
            //                TestMode = Convert.ToInt32(reader["test_mode"]),
            //                GID = Convert.ToInt32(reader["cabinet_id"]),
            //                CID = Convert.ToString(reader["channel_num"]),
            //                IsAll = Convert.ToInt32(reader["isAll"]),
            //                StepNum = Convert.ToInt32(reader["step_num"]),
            //                StepType = Convert.ToInt32(reader["step_type"]),
            //                StepName = DicHelper.RetrieveStepName(Convert.ToInt32(reader["step_type"])),
            //                WorkType = Convert.ToInt32(reader["work_type"]),
            //                Cycle = Convert.ToString(reader["cycle"]),
            //                TestTime = Convert.ToInt32(reader["test_time"]),
            //                ChannelEfficiency = Convert.ToInt32(reader["Channel_efficiency"]),
            //                DC_outputVolt = Convert.ToSingle(reader["DC_outputVolt"]),
            //                DC_loadCurrent = Convert.ToSingle(reader["DC_loadCurrent"]),
            //                Load_temper1 = Convert.ToSingle(reader["Load_temper1"]),
            //                Load_temper2 = Convert.ToSingle(reader["Load_temper2"]),
            //                DC_busVolt = Convert.ToSingle(reader["DC_busVolt"]),
            //                Charge_cap = Convert.ToSingle(reader["Charge_cap"]),
            //                Discharge_cap = Convert.ToSingle(reader["Discharge_cap"]),
            //                Total_cap = Convert.ToSingle(reader["Total_cap"]),
            //                Step_time = Convert.ToSingle(reader["Step_time"]),
            //                Charge_energy = Convert.ToSingle(reader["Charge_energy"]),
            //                Discharge_energy = Convert.ToSingle(reader["Discharge_energy"]),
            //                Total_energy = Convert.ToSingle(reader["Total_energy"]),
            //                Power = Convert.ToSingle(reader["power"]),
            //                Diff_volt = Convert.ToSingle(reader["Diff_volt"]),
            //                Diff_current = Convert.ToSingle(reader["Diff_current"]),
            //                Aux_data = Convert.ToString(reader["Aux_data"]),
            //                Status_data = Convert.ToString(reader["Status_data"]),
            //                Sys_Time = Convert.ToString(reader["Sys_time"]),
            //                IsExtra = Convert.ToInt32(reader["isExtra"])
            //            };
            //            chlList.Add(chl);

            //        }
            //    }
            //}
            //catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
            //return chlList;
            #endregion
            Dictionary<int, string> stepDic = StepDictionary.getStepDic();
            int currentCycleNum = 0;
            int currentStepNum = 0;
            int count = 0;
            int countRecord = 0;//计算工步中的记录条数
            int firstSeqID = 0;
            List<string> chlList = new List<string>();
            //string sql = "select * from " + tableName + " where test_id = @testid and mid_id = @mid and cabinet_id = @gid and channel_num = @cid and isExtra = 0";
            //每次limit查询起始索引
            int startIndex = 0;
            //每次limit查询读取条数
            int number = 10000;
            int totalNum = TestHelper.QueryTestRecordNum(testId, ip, gid, mid, Convert.ToInt32(cid));
            OnInitProcessBarStep(totalNum, number);
            while (startIndex < totalNum)
            {
                //查询剩余不足number的数据
                if (startIndex + number > totalNum)
                {
                    number = totalNum - startIndex;
                }
                string sql = String.Format("call retriveAllChannelData('{0}','{1}',{2},{3},'{4}',{5},{6})", tableName, testId, mid, gid, cid, startIndex, number);
                try
                {
                    using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
                    {
                        //cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", testId));
                        //cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@mid", mid));
                        //cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@gid", gid));
                        //cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", cid));
                        DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd);
                        StringBuilder sb = new StringBuilder();
                        while (reader.Read())
                        {
                            //Console.WriteLine("拼接前:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            //第一条记录
                            if (count == 0)
                            {
                                firstSeqID = Convert.ToInt32(reader["seq_id"]);
                                currentCycleNum = Convert.ToInt32(reader["cycle"]);
                                currentStepNum = Convert.ToInt32(reader["step_num"]);
                            }
                            sb.Append(ChannelStrHelper.strHelper[0]);sb.Append( Convert.ToString(reader["Aux_data"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[1]);sb.Append( Convert.ToInt32(reader["Channel_efficiency"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[2]);sb.Append( Convert.ToSingle(reader["Charge_cap"]) );sb.Append( "#/");
                            sb.Append(ChannelStrHelper.strHelper[3]);sb.Append( Convert.ToSingle(reader["Charge_energy"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[4]);sb.Append( Convert.ToString(reader["channel_num"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[5]);sb.Append( Convert.ToString(reader["cycle"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[6]);sb.Append( Convert.ToSingle(reader["DC_busVolt"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[7]);sb.Append( Convert.ToSingle(reader["DC_loadCurrent"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[8]);sb.Append( Convert.ToSingle(reader["DC_outputVolt"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[9]);sb.Append( Convert.ToSingle(reader["Diff_current"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[10]);sb.Append( Convert.ToSingle(reader["Diff_volt"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[11]);sb.Append( Convert.ToSingle(reader["Discharge_cap"]) );sb.Append( "@/");
                            sb.Append(ChannelStrHelper.strHelper[12]);sb.Append( Convert.ToSingle(reader["Discharge_energy"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[13]);sb.Append( Convert.ToInt32(reader["cabinet_id"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[14]);sb.Append( Convert.ToInt32(reader["isAll"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[15]);sb.Append( Convert.ToInt32(reader["isExtra"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[16]);sb.Append( Convert.ToSingle(reader["Load_temper1"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[17]);sb.Append( Convert.ToSingle(reader["Load_temper2"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[18]);sb.Append( Convert.ToSingle(reader["power"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[19]);sb.Append((firstSeqID + count));sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[20]);sb.Append( Convert.ToString(reader["Status_data"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[21]);sb.Append( Convert.ToSingle(reader["Step_time"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[22]);sb.Append( stepDic[Convert.ToInt32(reader["step_type"])] );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[23]);sb.Append( Convert.ToInt32(reader["step_num"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[24]);sb.Append( Convert.ToInt32(reader["step_type"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[25]);sb.Append( Convert.ToString(reader["Sys_time"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[26]);sb.Append( Convert.ToString(reader["test_id"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[27]);sb.Append( Convert.ToInt32(reader["test_mode"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[28]);sb.Append( Convert.ToInt32(reader["test_time"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[29]);sb.Append( Convert.ToSingle(reader["Total_cap"]) );sb.Append( "%/");
                            sb.Append(ChannelStrHelper.strHelper[30]);sb.Append( Convert.ToSingle(reader["Total_energy"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[31]);sb.Append( Convert.ToInt32(reader["work_type"]) );sb.Append(ChannelStrHelper.splitComb);
                            sb.Append(ChannelStrHelper.strHelper[32]);sb.Append( Convert.ToInt32(reader["pulse_num"]) );sb.Append( "&/}");
                            chlList.Add(sb.ToString());
                            //循环号改变
                            if (currentCycleNum != Convert.ToInt32(reader["cycle"]))
                            {
                                recordcount.Add(countRecord);
                                currentCycleNum = Convert.ToInt32(reader["cycle"]);
                                countRecord = 0;
                            }
                            else
                            {
                                //循环号不变，工步号改变
                                if (currentStepNum != Convert.ToInt32(reader["step_num"]))
                                {
                                    recordcount.Add(countRecord);
                                    currentStepNum = Convert.ToInt32(reader["step_num"]);
                                    countRecord = 0;
                                }
                            }
                            //worktype不为100
                            if (Convert.ToInt32(reader["work_type"]) != 100)
                            {
                                worktypeDic.Add(Convert.ToInt32(reader["seq_id"]), Convert.ToInt32(reader["work_type"]));
                            }
                            count++;
                            countRecord++;
                            sb.Clear();
                        }                   
                        OnAddProcessBarStep();
                    }
                }
                catch (Exception ex) 
                {
                    Console.WriteLine(ex.Message + ex.StackTrace);
                }
                startIndex = startIndex + number;
            }
            return chlList;
        }
        //public static List<RecordData> RetriveAllChannelData2(string testId, int mid, int gid, string cid, string tableName)
        //{
        //    List<RecordData> chlList = new List<RecordData>();
        //    string sql = "select * from " + tableName + " where test_id = @testid and mid_id = @mid and cabinet_id = @gid and channel_num = @cid and isExtra = 0";
        //    try
        //    {
        //        using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
        //        {
        //            cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", testId));
        //            cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@mid", mid));
        //            cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@gid", gid));
        //            cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", cid));
        //            DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd);
        //            StringBuilder sb = new StringBuilder();
        //            while (reader.Read())
        //            {
        //                RecordData rd = new RecordData();
        //                sb.Append("{Aux_data=" + Convert.ToString(reader["Aux_data"]) + "/");
        //                sb.Append("ChannelEfficiency=" + Convert.ToInt32(reader["Channel_efficiency"]) + "/");
        //                sb.Append("Charge_cap=" + Convert.ToSingle(reader["Charge_cap"]) + "/");
        //                rd.Charge_cap = Convert.ToSingle(reader["Charge_cap"]);
        //                sb.Append("Charge_energy=" + Convert.ToSingle(reader["Charge_energy"]) + "/");
        //                sb.Append("CID=" + Convert.ToString(reader["channel_num"]) + "/");
        //                sb.Append("Cycle=" + Convert.ToString(reader["cycle"]) + "/");
        //                rd.CycleNum = Convert.ToInt32(reader["cycle"]);
        //                sb.Append("DC_busVolt=" + Convert.ToSingle(reader["DC_busVolt"]) + "/");
        //                sb.Append("DC_loadCurrent=" + Convert.ToSingle(reader["DC_loadCurrent"]) + "/");
        //                sb.Append("DC_outputVolt=" + Convert.ToSingle(reader["DC_outputVolt"]) + "/");
        //                sb.Append("Diff_current=" + Convert.ToSingle(reader["Diff_current"]) + "/");
        //                sb.Append("Diff_volt=" + Convert.ToSingle(reader["Diff_volt"]) + "/");
        //                sb.Append("Discharge_cap=" + Convert.ToSingle(reader["Discharge_cap"]) + "/");
        //                rd.Discharge_cap = Convert.ToSingle(reader["Discharge_cap"]);
        //                sb.Append("Discharge_energy=" + Convert.ToSingle(reader["Discharge_energy"]) + "/");
        //                sb.Append("GID=" + Convert.ToInt32(reader["cabinet_id"]) + "/");
        //                sb.Append("IsAll=" + Convert.ToInt32(reader["isAll"]) + "/");
        //                sb.Append("IsExtra=" + Convert.ToInt32(reader["isExtra"]) + "/");
        //                sb.Append("Load_temper1=" + Convert.ToSingle(reader["Load_temper1"]) + "/");
        //                sb.Append("Load_temper2=" + Convert.ToSingle(reader["Load_temper2"]) + "/");
        //                sb.Append("Power=" + Convert.ToSingle(reader["power"]) + "/");
        //                sb.Append("SeqId=" + Convert.ToInt32(reader["seq_id"]) + "/");
        //                sb.Append("Status_data=" + Convert.ToString(reader["Status_data"]) + "/");
        //                sb.Append("Step_time=" + Convert.ToSingle(reader["Step_time"]) + "/");
        //                sb.Append("StepName=" + DicHelper.RetrieveStepName(Convert.ToInt32(reader["step_type"])) + "/");
        //                sb.Append("StepNum=" + Convert.ToInt32(reader["step_num"]) + "/");
        //                rd.StepNum = Convert.ToInt32(reader["step_num"]);
        //                sb.Append("StepType=" + Convert.ToInt32(reader["step_type"]) + "/");
        //                sb.Append("Sys_Time=" + Convert.ToString(reader["Sys_time"]) + "/");
        //                sb.Append("TestId=" + Convert.ToString(reader["test_id"]) + "/");
        //                sb.Append("TestMode=" + Convert.ToInt32(reader["test_mode"]) + "/");
        //                sb.Append("TestTime=" + Convert.ToInt32(reader["test_time"]) + "/");
        //                sb.Append("Total_cap=" + Convert.ToSingle(reader["Total_cap"]) + "/");
        //                rd.Total_cap = Convert.ToSingle(reader["Total_cap"]);
        //                sb.Append("Total_energy=" + Convert.ToSingle(reader["Total_energy"]) + "/");
        //                sb.Append("WorkType=" + Convert.ToInt32(reader["work_type"]) + "/}");
        //                rd.WorkType = Convert.ToInt32(reader["work_type"]);
        //                rd.ChannelData = sb.ToString();
        //                chlList.Add(rd);
        //                sb.Clear();
        //            }
        //        }
        //    }
        //    catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
        //    return chlList;
        //}
        /// <summary>
        /// 查询所有执行的工步
        /// </summary>
        /// <param name="testId"></param>
        /// <param name="gid"></param>
        /// <param name="cid"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static List<StepDetial> RetriveStepDetial(string testId, int mid, int gid, string cid, string tableName)
        {
            List<StepDetial> stepDetial = new List<StepDetial>();
            string sql = "select *,count(*) as count from " + tableName + " where test_id=@testid and mid_id = @mid and cabinet_id = @gid and channel_num = @cid "
                + "and work_type=@worktype GROUP BY cycle,step_num,step_type order by seq_id";
            try
            {
                DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
                cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", testId));
                cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@gid", gid));
                cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@mid", mid));
                cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cid", Convert.ToString(cid)));
                cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@worktype", 100));
                using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
                {

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            StepDetial step = new StepDetial()
                            {
                                startId = Convert.ToInt32(reader["seq_id"]),
                                DetialCount = Convert.ToInt32(reader["count"]),
                                StepNum = Convert.ToInt32(reader["step_num"]),
                                StepType = Convert.ToInt32(reader["step_type"]),
                                CycleNum = Convert.ToString(reader["cycle"]),
                            };
                            stepDetial.Add(step);
                        }
                    }

                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
            return stepDetial;
        }
        /// <summary>
        /// 查询通道数据为并联模式还是独立模式
        /// </summary>
        /// <param name="testId"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static string IsParallel(string testId, string tableName)
        {
            string cid = "";
            string sql = "select channel_num from " + tableName + " where test_id=@testid and isAll>0 limit 1";
            try
            {
                DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
                cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@testid", testId));
                using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            cid = Convert.ToString(reader["channel_num"]);
                        }
                    }
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
            return cid;
        }
    }
}

